

local TaskSequence = class("TaskSequence",function()
    return display.newNode()
end)

function TaskSequence:ctor()
    self.tasks = {}
end

function TaskSequence:start()
    self.taskLength = math.max(#self.tasks,1) 
    self.loadingIdx = 0
    self:scheduleUpdate( handler(self, self.updateLoading))
end

function TaskSequence:setFinishCallback(cb)
	self._finishCallback = cb
end

function TaskSequence:setProgressCallback(cb)
	self._progressCB = cb
end

function TaskSequence:updateLoading()
    self.loadingIdx = self.loadingIdx + 1

    if self.loadingIdx > self.taskLength then
        self:unscheduleUpdate()
        if self._finishCallback then
            self._finishCallback(self)
        end
        self:removeFromParent()
    else
        local task = self.tasks[self.loadingIdx]
        if task then
            task()
            if self._progressCB then
            	self._progressCB(self, self:getPercent())
            end
        end
    end

end

function TaskSequence:addTask(task)
    table.insert(self.tasks,task)
    return #self.tasks
end

function TaskSequence:getPercent()
	local percent = math.floor((self.loadingIdx/self.taskLength)*100)
	return percent
end

return TaskSequence